// pages/category/category.js
const colorUtil = require('../../utils/color')

const WXAPI = require('../../wxapi/main')
const app = getApp();
import Toast from 'tdesign-miniprogram/toast/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    categories: [{
      "name":"包间",
      "scrollId":"1"
    },{
      "name":"大厅",
      "scrollId":"2"
    }],
    equipmentIconPic:{
      "xbox":"https://7072-prod-8g7u9tmqac56ab70-1318102458.tcb.qcloud.la/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230524105318.png?sign=6e7879397cddb9b1b6354d48767d19b1&t=1684896964",
      "ps":"https://7072-prod-8g7u9tmqac56ab70-1318102458.tcb.qcloud.la/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230524105321%20(3).jpg?sign=96c89849a2a5e8fa29f6ad712d527823&t=1684897020",
      "switch":"https://7072-prod-8g7u9tmqac56ab70-1318102458.tcb.qcloud.la/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230524105321%20(1).jpg?sign=e4100934bb55a294ccb84f0918ed619e&t=1684896998"
      ,"vr":"https://7072-prod-8g7u9tmqac56ab70-1318102458.tcb.qcloud.la/vr.png?sign=6edb1b493667325dda84c07d6c6a81cc&t=1686066105"
    },
    goodsWrap: [],
    categorySelected: 1,
    goodsToView: "",
    categoryToView: "",
    hall:[],
    privateRoom:[],
    showData:[],
    itemWidth:"",
    buttonMarginTop:"",
    userInfo:{},
    colorMap:{},
    selectData:{},
    interval:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    app.queryUser();

    this.setData({
      userInfo:wx.getStorageSync('userInfo')
    })
      
    const systemInfo = wx.getSystemInfoSync();
    var screenWidth = systemInfo.screenWidth;
    var margin = screenWidth * 20 / 750;
    var itemWidth = (screenWidth - 4 * margin) / 4;
    var buttonMarginTop=(itemWidth * 1.5-margin *2)/2
    

    this.setData({
       itemWidth,
       buttonMarginTop
    })
    this.initData();
  },
 async startTime(e) {
    
  try {
    const res = await wx.showModal({
      title: '确认',
      content: '是否开启当前机位'
    })
    if (res.confirm) {
      WXAPI.startTime(e.currentTarget.dataset.id).then(res => {
        if (res.code == 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: "开机成功",
            theme: 'success',
            direction: 'column',
          });
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '开机失败:' + (res.msg ||  res.message ),
            theme: 'error',
            direction: 'column',
          });
        }
        this.initData();
  
      })
    } else if (res.cancel) {
      return;
    }
  } catch (e) {
    console.error(e)
  }
   
  },


  formatTime(seconds) {
    var hours = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds % 3600) / 60);
    var remainingSeconds = seconds % 60;
  
    var timeString = '';
    if (hours > 0) {
      timeString += hours + '时 ';
    }
    if (minutes > 0) {
      timeString += minutes + '分 ';
    }
    if (remainingSeconds > 0) {
      timeString += remainingSeconds + '秒';
    }
  
    return timeString.trim();
  },


  confirmEndtime(e) {

    WXAPI.endTime(e.currentTarget.dataset.id).then(res => {
      if (res.order_no) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: "关机成功",
          theme: 'success',
          direction: 'column',
        });

        setTimeout(() => {
              wx.navigateTo({
                url: `/pages/settlement/index?order_no=${res.order_no}`
              })
        }, 500)
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '开机失败:' + (res.msg ||  res.message ),
          theme: 'error',
          direction: 'column',
        });
      }
      this.initData();
    })
  },
  async endTime(e) {
    try {
      const res = await wx.showModal({
        title: '确认',
        content: '是否结束当前机位'
      })
      if (res.confirm) {
        this.confirmEndtime(e)
      } else if (res.cancel) {
        return;
      }
    } catch (e) {
      console.error(e)
    }
    
  },
  initData() {
    wx.showNavigationBarLoading();
    this.getGoodsList();
  },
  toDetailsTap: function (e) {
    var userInfo=wx.getStorageSync("userInfo");
    if(!userInfo){
        this.setData({
        authVisible:true,
        selectData:e.currentTarget.dataset.data
        })
        return;
    }
    
    wx.navigateTo({
      url: "/pages/venue-details/index?data=" + encodeURIComponent(JSON.stringify(e.currentTarget.dataset.data))
    })
  },
  goUrl(){
    wx.navigateTo({
      url: "/pages/venue-details/index?data=" + encodeURIComponent(JSON.stringify(this.data.selectData))
    })
  },
  getGoodsList: function() {
    let colorMap=this.data.colorMap
    WXAPI.queryVenue({
    }).then(res=> {
      var venueList=res;
      var hall=[];
      var privateRoom=[];
      venueList.forEach((element,index) => {
        element.play_duration_str = this.formatTime(element.play_duration)
        element.equipment_list.forEach(tag => {
          if (!colorMap[tag])
            colorMap[tag] = colorUtil.getRandomColor()
        })
        if(element.type==1){
          hall.push(element);
        }else{
          privateRoom.push(element)
        }
      });

      wx.hideNavigationBarLoading();
      if (this.data.interval !== null) {
        clearInterval(this.data.interval)
      }
      var interval=setInterval(()=>{
        hall.forEach(item => {
          item.play_duration += 1
          item.play_duration_str = this.formatTime(item.play_duration)
        })
        privateRoom.forEach(item => {
          item.play_duration += 1
          item.play_duration_str = this.formatTime(item.play_duration)
        })
        this.setData({
          hall: hall,
          privateRoom: privateRoom,
          showData:this.data.categorySelected==2?hall:privateRoom,
          colorMap
        })
      },1000)
      this.setData({
        interval
      })
      this.setData({
        interval:interval
      })
    }).catch((e) => {

      wx.hideNavigationBarLoading();
    });
  },
  onCategoryClick: function(e) {
    
    let type = e.detail.value;
    console.log(e)
    this.setData({
      goodsToView: type,
      categorySelected: type,
      showData:type==1?this.data.privateRoom:this.data.hall
    })
    

  },
  
})